/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frontera;

import Control.CrudCliente;
import Control.CrudCompra;
import Entidad.Cliente;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author felipe
 */
public class PanelCliente extends javax.swing.JPanel {

    
    public static DefaultTableModel dtmclientes;
    public double idCliente = 0;
    
    /**
     * Creates new form PanelCliente
     */
    public PanelCliente() {
        initComponents();
        baseDatos();
        inicializar();
    }
    
    public void inicializar(){

        
        dtmclientes = new DefaultTableModel(new Object[][]{
        }, new String[] {"Nombre", "ID", "Teléfono", "Dirección", "Email"}){
                };
        
        TablaClientes.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        TableColumnModel tcm = TablaClientes.getColumnModel();
        DiseñoColumna DC = new DiseñoColumna(Color.orange);
        
        
        TablaClientes.setModel(dtmclientes);
        
        for(Entidad.Cliente p: CrudCliente.bringAll()){

            dtmclientes.addRow(new Object[]{p.getNombre(),p.getID(), p.getTelefono(), p.getDireccion()});
        }
        
        TablaClientes.setDefaultRenderer(Object.class, new FormatoTabla());
        tcm.getColumn(0).setCellRenderer(DC);
        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        TablaClientes = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        listaOrden = new javax.swing.JComboBox();

        setPreferredSize(new java.awt.Dimension(1000, 869));

        jScrollPane1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jScrollPane1KeyPressed(evt);
            }
        });

        TablaClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        TablaClientes.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                TablaClientesKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(TablaClientes);

        jLabel1.setText("Ordenar clientes por:");

        listaOrden.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "...", "Numero de Compras", "Dinero Gastado", "Numero de Productos" }));
        listaOrden.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listaOrdenActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 568, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addComponent(jLabel1)
                        .addGap(39, 39, 39)
                        .addComponent(listaOrden, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(383, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(listaOrden, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(546, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jScrollPane1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jScrollPane1KeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jScrollPane1KeyPressed

    private void TablaClientesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TablaClientesKeyPressed
        // TODO add your handling code here:
                if (evt.getKeyChar() == KeyEvent.VK_ENTER){
        try{
            int fila = TablaClientes.getSelectedRow();
            double id = 0;
              try{   
                  id = (double)dtmclientes.getValueAt(fila,1);
              }
              catch(Exception g){
              }
              idCliente = id;
              if(idCliente != 0){
                  ClienteInf ventana = new ClienteInf(idCliente);
                  ventana.setVisible(true);
              }
              else JOptionPane.showMessageDialog(TablaClientes, "Seleccione Cliente");
              evt.consume();
        }
        catch(Exception e){
            System.out.print("exception");
            e.printStackTrace();
            
        }
        }
    }//GEN-LAST:event_TablaClientesKeyPressed

    private void listaOrdenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listaOrdenActionPerformed
        // TODO add your handling code here:
        String orden = (String)listaOrden.getSelectedItem();
        List<Cliente> clientes = CrudCliente.bringAll();
        double [][] ord= new double[clientes.size()][2];
        if (orden.equals("Numero de Compras")){
        dtmclientes = new DefaultTableModel(new Object[][]{
        }, new String[] {"Nombre", "ID", "Numero de Compras"}){
                };
        TablaClientes.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        TablaClientes.setModel(dtmclientes);
        int i=0;
        for(Entidad.Cliente p: clientes){
            ord[i][0]=i;
           int j=0;
           for(Entidad.Compra q: CrudCompra.bringAll()){
           if (q.getCliente().getID()==p.getID()){
               j++;
            }
        }
            ord[i][1]=j;
            i++;
        }
         ordenar(ord);
        }
        
        if (orden.equals("Numero de Productos")){
        dtmclientes = new DefaultTableModel(new Object[][]{
        }, new String[] {"Nombre", "ID", "Numero de Productos"}){
                };
        
        TablaClientes.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        TablaClientes.setModel(dtmclientes);
        
        int i=0;
        for(Entidad.Cliente p: clientes){
           ord[i][0]=i;
           double j=0;
           for(Entidad.Compra q: CrudCompra.bringAll()){
           if (q.getCliente().getID()==p.getID()){
               j+=q.getProducto().size();
            }
        }
            ord[i][1]=j;
            i++;
        }
        ordenar(ord);
        }
        
        if (orden.equals("Dinero Gastado")){
        dtmclientes = new DefaultTableModel(new Object[][]{
        }, new String[] {"Nombre", "ID", "Dinero Gastado"}){
                };
        
        TablaClientes.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        TablaClientes.setModel(dtmclientes);
        int i=0;
        for(Entidad.Cliente p: clientes){
            ord[i][0]=i;
           double j=0;
           for(Entidad.Compra q: CrudCompra.bringAll()){
           if (q.getCliente().getID()==p.getID()){
               j+=q.getValor();
            }
        }
            ord[i][1]=j;
            i++;
        }
        ordenar(ord);
        }
        
        if (orden.equals("...")){
            inicializar();
        }
        
        
        
    }//GEN-LAST:event_listaOrdenActionPerformed
    
    public void ordenar(double [][] a){
        TableColumnModel tcm = TablaClientes.getColumnModel();
        DiseñoColumna DC = new DiseñoColumna(Color.orange);
       
        for(int i=0; i<a.length-1; i++){
            int max=i;
            for (int j=i+1; j<a.length; j++){
                    if(a[j][1]>a[max][1]){
                            max=j;
                    }
            }
            if (i!=max){
                double aux=a[i][1];
                a[i][1]=a[max][1];
                a[max][1]=aux;
                aux=a[i][0];
                a[i][0]=a[max][0];
                a[max][0]=aux;
            }
        }
        List<Cliente> p = CrudCliente.bringAll();
        for(int i=0;i<a.length;i++){
            dtmclientes.addRow(new Object[]{p.get((int)a[i][0]).getNombre(),p.get((int)a[i][0]).getID(),a[i][1]});
        }
        TablaClientes.setDefaultRenderer(Object.class, new FormatoTabla());
        tcm.getColumn(0).setCellRenderer(DC);
}
    
    
    
    
    public JTable getTabla(){
        return TablaClientes;
    }
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TablaClientes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox listaOrden;
    // End of variables declaration//GEN-END:variables

    private void baseDatos() {
        CrudCliente.crearCliente("Pepe", 333,"Calle Falsa 123", 123454321);
        CrudCliente.crearCliente("Jose", 5656,"Calle Nueva 1234", 13579);
        CrudCliente.crearCliente("Luis", 999,"Calle 1023", 1111111);
    }
}
